//
//  BaseAFManager.m
//  ZLSQ_Staff
//
//  Created by ihope99 on 2017/3/29.
//  Copyright © 2017年 FFB. All rights reserved.
//

#import "BaseAFManager.h"
#import "AFNetworking.h"
#import "BaseADViewController.h"


static const NSTimeInterval kTimeoutInterval = 15.0;



@implementation BaseAFManager


+(void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure
{


    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    session.requestSerializer.timeoutInterval = kTimeoutInterval;
    
    
    [session GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"成功");
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
        NSLog(@"%@",error);
        
        if (failure) {
            
            failure(error);
        }
    }];
}

+ (void)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure rootCtrl:(BaseADViewController *)rootCtrl
{
//    NSLog(@"%@?%@", URLString, [BaseAFManager appendParameters:parameters]);

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
    
//    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    session.requestSerializer.timeoutInterval = kTimeoutInterval;
    
    
    if (rootCtrl) {
           [rootCtrl StartLoading];
    }
    
    [session POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功,%@",responseObject);
        if (rootCtrl){
            [rootCtrl StopLoading];
        }
        if (success) {
            NSDictionary * dict =(NSDictionary *)responseObject;
            if (dict && [dict isKindOfClass:[NSDictionary class]])
            {
                NSInteger iCode = [dict[@"status"] intValue];
                if (iCode == 1101){
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"Login_Exit" object:nil];
                    return;
                }
            }
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
        NSLog(@"%@",error);
        if (rootCtrl) {
            [rootCtrl StopLoading];
            [rootCtrl showMsg:@"请求失败"];
        }
        if (failure) {
            failure(error);
        }
    }];
}

+(void)POSTImage:(NSString *)URLString parameters:(id)parameters FileDict:(NSDictionary *)imageDict success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure
{
    NSString *url = [NSString stringWithFormat:@"%@%@", URLString, URLString];
    NSLog(@"%@?%@", url, [BaseAFManager appendParameters:parameters]);
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",nil];
    session.requestSerializer.timeoutInterval = kTimeoutInterval;
    
    
    
    [session POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSString *key in imageDict.allKeys) {
            id value = [imageDict objectForKey:key];
            if ([value isKindOfClass:[NSArray class]]) {
                for (NSInteger i = 0; i < [value count]; i ++ ) {
                    UIImage *image = value[i];
                    NSData *data ;
                    if ( UIImagePNGRepresentation(image)==nil) {
                        data = UIImageJPEGRepresentation(image, 1);
                    }else{
                        data = UIImagePNGRepresentation(image);
                    }
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = [NSString stringWithFormat:@"yyyyMMddHHmmss%lu",i];
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
                    [formData appendPartWithFileData:data name:key fileName:fileName mimeType:@"image/png"];
                }
            }
            else {
                NSData *data ;
                if ( UIImagePNGRepresentation(value)==nil) {
                    data = UIImageJPEGRepresentation(value, 1);
                }else{
                    data = UIImagePNGRepresentation(value);
                }
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
                [formData appendPartWithFileData:data name:key fileName:fileName mimeType:@"image/png"];
            }
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
        if (success) {
            NSDictionary * dict =(NSDictionary *)responseObject;
            if (dict && [dict isKindOfClass:[NSDictionary class]])
            {
                NSInteger iCode = [dict[@"status"] intValue];
                if (iCode == 1101){
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"Login_Exit" object:nil];
                    return;
                }
            }
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%lu",task.taskIdentifier);
        NSLog(@"%@",error);
        
        if (failure) {
            failure(error);
        }
    }];
}


+(NSString *)appendParameters:(id)parameters{
    NSDictionary *dict = (NSDictionary *)parameters;
    NSArray *allKeys = dict.allKeys;
    NSString *string = @"";
    for (NSString *key in allKeys) {
        string = [string stringByAppendingFormat:@"%@%@=%@", string.length==0?@"":@"&", key,dict[key]];
    }
    return string;
}


@end

